<template>
  <ScreenFit>
    <BaseLayout>
      <template v-slot:aside-search>
        <SelectRearer></SelectRearer>
      </template>
      <template v-slot:aside-content>
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="精准巡查" name="check">
            <div class="checkInfo">
              <div class="baseInfo">
                <div class="baseInfo-info">
                  <div class="baseInfo-info-item">
                    <svgIcon name="feeddate" width="50px" height="50px"></svgIcon>
                    <div class="detail">
                      <div class="top">饲养天龄</div>
                      <div class="bottom">{{ dayold || '-' }}</div>
                    </div>
                  </div>
                  <div class="baseInfo-info-item">
                    <svgIcon name="stock" width="50px" height="50px"></svgIcon>
                    <div class="detail">
                      <div class="top">存栏(只)</div>
                      <div class="bottom">{{ stockNum || '-' }}</div>
                    </div>
                  </div>
                  <div class="baseInfo-info-item">
                    <svgIcon name="weight" width="50px" height="50px"></svgIcon>
                    <div class="detail">
                      <div class="top">均重(kg)</div>
                      <div class="bottom">{{ formattedWeight || '-' }}</div>
                    </div>
                  </div>
                  <div class="baseInfo-info-item">
                    <svgIcon name="death" width="50px" height="50px"></svgIcon>
                    <div class="detail">
                      <div class="top">近7日死淘率</div>
                      <div class="bottom">{{ formattedDeadAmoyRate }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="remotePlan">
                <div class="remotePlan-title" @click="toggle1">
                  远程巡查计划
                  <el-icon :class="{ rotated: isExpanded1 }">
                    <ArrowRightBold />
                  </el-icon>
                </div>
                <div class="remotePlan-content">
                  <transition name="slide">
                    <div v-show="isExpanded1" class="expand-content">
                      <el-timeline style="max-width: 600px; padding: 5px 0 0">
                        <el-timeline-item
                          v-for="(activity, index) in planList"
                          :key="index"
                          :icon="activity.icon"
                          :type="activity.type"
                          :color="activity.color"
                          :size="activity.size"
                          :hollow="activity.hollow"
                          :timestamp="activity.timestamp"
                        >
                          <div>
                            <el-tag type="success" effect="dark" v-if="activity.status">
                              {{ activity.statusTitle }}
                            </el-tag>
                            <el-tag type="warning" effect="dark" v-else>
                              {{ activity.statusTitle }}
                            </el-tag>
                            {{ activity.content }}
                          </div>
                          <span style="color: #8c8c8c; font-size: 12px">
                            {{ activity.people }}
                          </span>
                        </el-timeline-item>
                      </el-timeline>
                      <!-- <el-pagination
                        layout="prev, pager, next"
                        size="small"
                        @change="planPageChange"
                        :total="planListParams.total"
                        v-model:page-size="planListParams.pageSize"
                        v-model:current-page="planListParams.pageNum"
                      /> -->
                      <div @click="planRowClick('wens_inspection_plans')" class="more">
                        查看更多
                      </div>
                    </div>
                  </transition>
                </div>
              </div>
              <div class="remotePlan">
                <div class="remotePlan-title" @click="toggle2">
                  告警异常信息
                  <el-icon :class="{ rotated: isExpanded2 }">
                    <ArrowRightBold />
                  </el-icon>
                </div>
                <div class="remotePlan-content">
                  <transition name="slide">
                    <div v-show="isExpanded2" class="expand-content">
                      <el-timeline style="max-width: 600px; padding: 5px 0 0">
                        <el-timeline-item
                          v-for="(activity, index) in patrolAlarmbyRearerList"
                          :key="index"
                          :icon="activity.icon"
                          :type="activity.type"
                          :color="activity.color"
                          :size="activity.size"
                          :hollow="activity.hollow"
                          :timestamp="activity.timestamp"
                          style="cursor: pointer"
                          @click="selectAlarmInfo(activity.id, activity.flockId)"
                        >
                          <el-tag type="success" effect="dark" v-if="activity.status">
                            {{ activity.statusTitle }}
                          </el-tag>
                          <el-tag type="warning" effect="dark" v-else>
                            {{ activity.statusTitle }}
                          </el-tag>
                          {{ activity.content }}
                        </el-timeline-item>
                      </el-timeline>
                      <!-- <el-pagination
                        layout="prev, pager, next"
                        size="small"
                        @change="alarmPageChange"
                        :total="listParams.total"
                        v-model:page-size="listParams.pageSize"
                        v-model:current-page="listParams.pageNum"
                      /> -->
                      <div @click="planRowClick('wens_patrol_alarm')" class="more">查看更多</div>
                    </div>
                  </transition>
                </div>
              </div>
              <div class="remotePlan">
                <div class="remotePlan-title" @click="toggle3">
                  现场巡查任务
                  <el-icon :class="{ rotated: isExpanded3 }">
                    <ArrowRightBold />
                  </el-icon>
                </div>
                <div class="remotePlan-content">
                  <transition name="slide">
                    <div v-show="isExpanded3" class="expand-content">
                      <el-timeline style="max-width: 600px; padding: 5px 0 0">
                        <el-timeline-item
                          v-for="(activity, index) in taskList"
                          :key="index"
                          :icon="activity.icon"
                          :type="activity.type"
                          :color="activity.color"
                          :size="activity.size"
                          :hollow="activity.hollow"
                          :timestamp="activity.timestamp"
                        >
                          <div>
                            <el-tag type="success" effect="dark" v-if="activity.status">
                              {{ activity.statusTitle }}
                            </el-tag>
                            <el-tag type="warning" effect="dark" v-else>
                              {{ activity.statusTitle }}
                            </el-tag>
                            {{ activity.content }}
                          </div>
                          <span style="color: #8c8c8c; font-size: 12px">
                            {{ activity.people }}
                          </span>
                        </el-timeline-item>
                      </el-timeline>
                      <!-- <el-pagination
                        layout="prev, pager, next"
                        size="small"
                        @change="taskPageChange"
                        :total="taskListParams.total"
                        v-model:page-size="taskListParams.pageSize"
                        v-model:current-page="taskListParams.pageNum"
                      /> -->
                      <div @click="planRowClick('wens_patrol_task')" class="more">查看更多</div>
                    </div>
                  </transition>
                </div>
              </div>
              <ServiceDetail1 :fAdoptDate="fAdoptDate" :fDelayDate="fDelayDate"></ServiceDetail1>
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-slot:main>
        <div class="main">
          <el-tabs v-model="activeName2" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="全域监控" name="tab1">
              <GlobalMonitoring :isShowIframe="!showDialog"></GlobalMonitoring>
            </el-tab-pane>
            <el-tab-pane label="告警核实" name="tab2">
              <AlarmCheck :isShowIframe="!showDialog" :fid="selected.fid"></AlarmCheck>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
    </BaseLayout>
  </ScreenFit>
  <linkDialog v-model="showDialog" :abnormal-iframe-param="iframeParam" />
</template>
<script setup>
import { onMounted, ref, computed } from 'vue'
import BaseLayout from '@/components/layouts/BaseLayout.vue'
import {
  getInspectionPlansByRearer,
  getFlockInfo,
  getPatrolAlarmByRearer,
  getPatrolTaskByRearer
} from '@/api/api'
import AlarmCheck from '@/components/RearerDetail/AlarmCheck.vue'
import GlobalMonitoring from '@/components/RearerDetail/GlobalMonitoring.vue'
import SelectRearer from '@/components/SelectRearer.vue'
import { useRoute, useRouter } from 'vue-router'
import { useBaseParamStore } from '@/stores/baseParams'
import ServiceDetail1 from '@/components/RearerDetail/ServiceDetail1.vue'
import linkDialog from '@/components/linkDialog.vue'
import Empty from '@/components/Empty.vue'

const baseParamStore = useBaseParamStore()
const route = useRoute()
const router = useRouter()
const activeName = ref('check')
const activeName2 = ref('tab2')

const fAdoptDate = ref('') // 进苗
const fDelayDate = ref('') // 上市
const dayold = ref('') // 在养天龄
const stockNum = ref('') // 在养数量
const weight = ref('') // 体重
const deadAmoyRate = ref('') // 死淘率
const iframeParam = ref('')
const showDialog = ref(false)

// 展开
const isExpanded1 = ref(true)
const isExpanded2 = ref(true)
const isExpanded3 = ref(true)
const toggle1 = () => {
  isExpanded1.value = !isExpanded1.value
}
const toggle2 = () => {
  isExpanded2.value = !isExpanded2.value
}
const toggle3 = () => {
  isExpanded3.value = !isExpanded3.value
}

const formattedDeadAmoyRate = computed(() => {
  return (deadAmoyRate.value * 100).toFixed(2) + '%'
})

const formattedWeight = computed(() => {
  const value = parseFloat(weight.value)
  return isNaN(value) ? '-' : value.toFixed(1)
})

// 更多跳转链接参数
const planRowClick = (param) => {
  iframeParam.value = param
  showDialog.value = true
}

const selected = ref({
  fid: '',
  flockId: ''
})
const selectAlarmInfo = (fid, flockId) => {
  // selected.value = {
  //   fid,
  //   flockId
  // }
  // console.log('selected.value', selected.value)
  // 构造新的查询参数对象
  const newQuery = {
    ...route.query,
    fid: fid,
    flockId: flockId
  }

  // 使用 router.replace 更新地址栏，不触发页面刷新
  router.replace({
    path: route.path,
    query: newQuery
  })
  setTimeout(() => {
    location.reload()
  }, 100)
  fetchFlockInfo()
}

// 获取猪群信息
const fetchFlockInfo = async () => {
  try {
    const res = await getFlockInfo({
      flockId: route.query.flockId
    })
    if (res && res.data) {
      fAdoptDate.value = res.data.fAdoptDate
      fDelayDate.value = res.data.fDelayDate
      dayold.value = res.data.dayold
      stockNum.value = res.data.stockNum
      weight.value = res.data.weight
      deadAmoyRate.value = res.data.deadAmoyRate
    }
  } catch (error) {
    console.error('获取获取告警详情信息失败:', error)
  }
}

// 获取计划列表
const planList = ref({})
const planListParams = ref({
  pageNum: 1,
  pageSize: 3,
  total: 0,
  loading: false,
  finished: false
})
const fetchInspectionPlansByRearer = async () => {
  try {
    const res = await getInspectionPlansByRearer({
      rearerId: decodeURIComponent(baseParamStore.baseParam.rearerId),
      pageSize: planListParams.value.pageSize,
      pageNo: planListParams.value.pageNum
    })
    if (res && res.data) {
      if (res.data.rows.length > 0) {
        planList.value = res.data.rows
        planList.value = planList.value.map((item) => {
          return {
            status: item.wens_isbuild,
            statusTitle: item.wens_isbuild ? '已巡查' : '待巡查',
            content: `${item.wens_biztype_title || ''}`,
            people: `巡查人：${item.wens_rearer_farm_wens_manager_name} `,
            timestamp: `创建时间：${item.wens_begin}`,
            color: item.wens_isbuild ? 'orange' : 'red'
          }
        })
        planListParams.value.total = res.data.totalCount
        if (res.data.rows.length < planListParams.value.pageSize) {
          planListParams.value.finished = true
        }
      } else {
        planListParams.value.finished = true
      }
    }
  } catch (error) {
    console.error('获取养户任务列表信息失败:', error)
  }
}
// 计划列表信息
const planPageChange = (pageNo) => {
  planListParams.value.pageNum = pageNo
  fetchInspectionPlansByRearer()
}

// 告警信息
const alarmPageChange = (pageNo) => {
  listParams.value.pageNum = pageNo
  fetchPatrolAlarmByRearer()
}
const patrolAlarmbyRearerList = ref([]) // 获取服务部告警任务列表
const listParams = ref({
  pageNum: 1,
  pageSize: 4,
  total: 0,
  loading: false,
  finished: false
})
// 获取根据养户id 获取告警信息列表
const fetchPatrolAlarmByRearer = async () => {
  try {
    const res = await getPatrolAlarmByRearer({
      rearerId: decodeURIComponent(baseParamStore.baseParam.rearerId),
      pageSize: listParams.value.pageSize,
      pageNo: listParams.value.pageNum
    })
    if (res && res.data) {
      if (res.data.rows.length > 0) {
        // if (listParams.value.pageNum == 1 && !selected.value.fid) {
        //   selected.value.fid = res.data.rows[0].id
        //   selected.value.flockId = res.data.rows[0].wens_flock_wens_easid
        //   fetchFlockInfo()
        // }
        patrolAlarmbyRearerList.value = res.data.rows
        patrolAlarmbyRearerList.value = patrolAlarmbyRearerList.value.map((item) => {
          return {
            status: item.wens_alarm_state == '1' ? false : true,
            statusTitle: item.wens_alarm_state_title,
            content: `${item.wens_event_type_title}${item.wens_alarm_level == '1' ? 'I' : 'II'}级告警`,
            timestamp: `告警时间：${item.wens_datetime}`,
            color: item.wens_alarm_state == '1' ? 'red' : 'orange',
            id: item.id,
            rearerId: item.wens_rearer_wens_easid,
            flockId: item.wens_flock_wens_easid
          }
        })
        listParams.value.total = res.data.totalCount
        if (res.data.rows.length < listParams.value.pageSize) {
          listParams.value.finished = true
        }
      } else {
        listParams.value.finished = true
      }
    }
  } catch (error) {
    console.error('获取告警信息列表失败:', error)
  }
}

// 获取任务列表
const taskList = ref({})
const taskListParams = ref({
  pageNum: 1,
  pageSize: 3,
  total: 0,
  loading: false,
  finished: false
})
const fetchPatrolTaskByRearer = async () => {
  try {
    const res = await getPatrolTaskByRearer({
      rearerId: decodeURIComponent(baseParamStore.baseParam.rearerId),
      pageSize: taskListParams.value.pageSize,
      pageNo: taskListParams.value.pageNum
    })
    if (res && res.data) {
      if (res.data.rows.length > 0) {
        taskList.value = res.data.rows
        taskList.value = taskList.value.map((item) => {
          return {
            status: item.wens_task_status == '1' ? false : true,
            statusTitle: item.wens_task_status_title,
            content: `${item.wens_rearer_name || ''}-${item.wens_patrol_type_title}`,
            people: `服务员：${item.wens_user_name || '-'} `,
            timestamp: `派发时间：${item.modifytime}`,
            color: item.wens_task_status == '1' ? 'orange' : 'green'
          }
        })
        taskListParams.value.total = res.data.totalCount
        if (res.data.rows.length < taskListParams.value.pageSize) {
          taskListParams.value.finished = true
        }
      } else {
        taskListParams.value.finished = true
      }
    }
  } catch (error) {
    console.error('获取养户任务列表信息失败:', error)
  }
}
// 任务列表信息
const taskPageChange = (pageNo) => {
  taskListParams.value.pageNum = pageNo
  fetchPatrolTaskByRearer()
}

onMounted(() => {
  fetchFlockInfo()
  fetchInspectionPlansByRearer()
  fetchPatrolAlarmByRearer()
  fetchPatrolTaskByRearer()
})
const handleClick = (tab, event) => {
  console.log(tab, event)
}
</script>

<style scoped lang="scss">
:deep(.el-tabs__item) {
  width: 100px;
}
:deep(.el-tabs) {
  height: 100%;
  .el-tabs__content {
    overflow: auto;
    height: 100%;
  }
}

.main {
  padding: 10px 20px;
  width: 100%;
  height: 100%;
}

.checkInfo {
  height: 100%;
  overflow-y: auto;
  padding: 0 10px;
  .baseInfo {
    margin-bottom: 15px;
    padding: 0 10px;
    &-info {
      display: flex;
      flex-wrap: wrap;
      &-item {
        width: 50%;
        display: flex;
        margin: 10px 0;
        .detail {
          display: flex;
          margin-left: 10px;
          flex-direction: column;
          .top {
            color: #ccc;
            font-size: 12px;
          }
          .bottom {
            font-size: 24px;
          }
        }
      }
    }
  }
  .remotePlan {
    width: 100%;
    &-title {
      height: 60px;
      background-image: linear-gradient(to right, #002f67, #0049a0);
      font-size: 16px;
      margin-bottom: 5px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 30px;
    }
    &-content {
      padding: 0 20px;
      width: 100%;
      display: flex;
      margin: 20px 0;
      .more {
        cursor: pointer;
        width: 100%;
        height: 50px;
        border-radius: 5px;
        background-color: #0049a0;
        font-weight: 100;
        font-size: 12px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #409eff;
        border: 1px solid #409eff;
      }
    }
  }
}

// 展开动画
.expand-content {
  width: 100%;
  overflow: hidden;
}
.slide-enter-active,
.slide-leave-active {
  transition: max-height 0.3s ease-out;
  overflow: hidden;
}
.slide-enter-from,
.slide-leave-to {
  max-height: 0;
}
.slide-enter-to,
.slide-leave-from {
  max-height: 200px; // 根据实际内容调整
}

// 箭头旋转
.remotePlan-title .el-icon {
  transition: transform 0.3s ease;
  font-size: 16px;
  margin-left: 8px;
}
.remotePlan-title .rotated {
  transform: rotate(90deg);
}
</style>
